<template>
  <div class="article-write-container animate__animated animate__fadeIn">
    <!-- 标题输入区域 -->
    <div class="input-section">
      <input
        v-model="articleTitle"
        type="text"
        placeholder="请输入文章标题"
        class="title-input animate__animated animate__fadeInDown"
      />
      <textarea
        v-model="articleDescription"
        placeholder="请输入文章概述"
        class="summary-input animate__animated animate__fadeInDown animate__delay-1s"
      ></textarea>
    </div>

    <!-- 编辑器区域 -->
    <div class="editor-wrapper animate__animated animate__fadeInUp animate__delay-2s">
      <Toolbar
        style="border-bottom: 1px solid #dcdfe6"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: calc(100vh - 300px); overflow-y: hidden;"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons animate__animated animate__fadeInUp animate__delay-3s">
      <button class="action-button save-button" @click="handleSave">
        <t-icon name="save" /> 保存草稿
      </button>
      <button class="action-button submit-button" @click="handleSubmit">
        <t-icon name="send" /> 发布文章
      </button>
    </div>
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css';
import 'animate.css';
import { onBeforeUnmount, ref, shallowRef } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { uploadImage} from '@/api/uploadApi';
import { submitArticle } from '@/api/articleApi';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/userStore';
import { storeToRefs } from 'pinia';

const userStore = useUserStore();
const { profile } = storeToRefs(userStore);

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 文章标题和概述
const articleTitle = ref('');
const articleDescription = ref('');

// 内容 HTML
const valueHtml = ref('');

const toolbarConfig = {};
const editorConfig = {
  placeholder: '请输入内容...'
};

editorConfig.MENU_CONF = {
  uploadImage: {
    customUpload: async (file, insertFn) => {
      const formData = new FormData();
      formData.append('file', file);

      try {
        const response = await uploadImage(formData);
        if (response.errno === 0) {
          insertFn(response.data.url);
          ElMessage({
            message: "图片上传成功",
            type: 'success',
          });
        } else {
          ElMessage({
            message: "图片上传失败",
            type: 'error',
          });
        }
      } catch (error) {
        console.error('图片上传出错:', error);
        ElMessage({
          message: "图片上传出错",
          type: 'error',
        });
      }
    }
  }
};

// 组件销毁时，销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor;
};

// 保存文章
const handleSave = async () => {
  if (!articleTitle.value || !articleDescription.value || !valueHtml.value) {
    ElMessage.warning('请完善文章内容');
    return;
  }
  try {
    const data = {
      title: articleTitle.value,
      description: articleDescription.value,
      userId: profile.value.id,
      content: valueHtml.value,
      status: 'DRAFT'
    };
    const response = await submitArticle(data);
    ElMessage.success('文章保存成功');
  } catch (error) {
    console.error('文章保存失败:', error);
    ElMessage.error('文章保存失败');
  }
};

// 提交文章
const handleSubmit = async () => {
  if (!articleTitle.value || !articleDescription.value || !valueHtml.value) {
    ElMessage.warning('请完善文章内容');
    return;
  }

  try {
    const data = {
      title: articleTitle.value,
      description: articleDescription.value,
      userId: profile.value.id,
      content: valueHtml.value,
      status: 'PUBLISHED'
    };
    const response = await submitArticle(data);
    ElMessage.success('文章发布成功');
  } catch (error) {
    console.error('文章发布失败:', error);
    ElMessage.error('文章发布失败');
  }
};

const mode = 'default';
</script>

<style scoped>
.article-write-container {
  height: 100%;
  padding: 20px;
  background-color: #ffffff;
}

.input-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.title-input,
.summary-input {
  width: 100%;
  padding: 12px 15px;
  font-size: 16px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  outline: none;
  transition: all 0.3s ease;
  background-color: #f8f9fa;
}

.title-input {
  font-size: 18px;
  font-weight: 500;
}

.summary-input {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

.title-input:focus,
.summary-input:focus {
  border-color: #409eff;
  background-color: #ffffff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.editor-wrapper {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  padding: 10px 0;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 24px;
  font-size: 16px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.save-button {
  background-color: #f2f6fc;
  color: #409eff;
}

.save-button:hover {
  background-color: #ecf5ff;
}

.submit-button {
  background-color: #409eff;
  color: white;
}

.submit-button:hover {
  background-color: #66b1ff;
}

.action-button:active {
  transform: scale(0.98);
}
</style>